package com.itanqing.qcim.mvc.exception;

import com.xiaohuoren.dubbo.common.bean.Result;
import com.xiaohuoren.dubbo.common.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author fengjun
 * @className GlobalExceptionHandler
 * @description
 * @date 2022年03月24日 下午6:45
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(AppException.class)
    public Result exceptionHandler(AppException e) {
        log.error("AppException:{}", e);
        String failMsg = e.getMessage();
        String code = e.getCode();
        if (ObjectUtils.isEmpty(code)) {
            code = "501";
        }
        return Result.create().fail(code, failMsg);
    }

    /**
     * 实体类 校验异常捕捉
     *
     * @param e
     * @return com.xiaohuoren.dubbo.common.bean.Result
     * @description
     * @author fengjun
     * @date 2022-03-24
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e) {
        return Result.create().fail("502", e.getBindingResult().getFieldError().getDefaultMessage());
    }
}